<?php
require_once('../libraryfiles/config.php');
if (empty($_GET['cat_p'])) {
    ?>
    <script type="text/javascript">
        //window.location = "<?php echo W_ROOT; ?>"
    </script>
    <?php
    //exit();
}
$content = 'index.php';
$searchby = isset($_GET['searchby']) ? $lang['CUSTOM_SEARCH'] : $lang['LATEST_PRODUCT'];
$cat_id = isset($_GET['cat_id']) ? (int) $_GET['cat_id'] : '';
$cat_p = isset($_GET['cat_p']) ? (int) $_GET['cat_p'] : '';
$category = isset($_GET['cat_p']) ? (int) $_GET['cat_p'] : $cat_id;
$category_id = isset($_GET['cat_id']) ? (int) $_GET['cat_id'] : $cat_id;
$subcat = isset($_GET['cat_id']) ? (int) $_GET['cat_id'] : '';
$qstring = "cat_p=" . isset($_GET['cat_p']) . "&amp;cat_id=" . $subcat;

/* by user */
$user_id = isset($_GET['user']) ? $_GET['user'] : @$_SESSION['user_pro'];
if($user_id =='none') {
    unset($_SESSION['user_pro']);
}
if (!empty($user_id) && $user_id !='none') {
    $_SESSION['user_pro'] = $user_id;
    $result = select(Tbluser::Tbluser, '', array(Tbluser::id => $user_id));
    $row_user = mysql_fetch_assoc($result);
    if (!empty($row_user)) {
        $company_name = $row_user[Tbluser::first_name];
    }
    $sql_user = ' AND p.' . Tblproduct::owner . '=' . $user_id;
    $userlink = '?user=' . $user_id;
} else {
    $sql_user = '';
    $userlink = '';
}
/* end by user */

$parent = $category;
$qstring = "cat_p=$parent";
if (!empty($parent)):
    $sql_1 = "SELECT id, parent_id FROM tblcategory WHERE parent_id = $parent";
    $result_1 = mysql_query($sql_1);
    $id = array();
    if (dbNumRows($result_1)) {
        while ($row_1 = mysql_fetch_assoc($result_1)) {
            $id[] = $row_1['id'];
        }
        $category = implode(',', $id);
    }
endif;
$site_title = (!empty($parent) ? special_char(getCategoryName($parent)) : $searchby);
require_once TMP_USER_PATH;
//for cate
$cateid = 8;
$show = 1;
$char = 20;
$obj = new by_category();
$more_value = 20;

/* color and brand */
if (!empty($_GET['color'])) {
    $mix = "AND mix.color_id='" . $_GET['color'] . "'";
} else if (!empty($_GET['size'])) {
    $mix = "AND mix.size_id='" . $_GET['size'] . "'";
} else if (!empty($_GET['brand'])) {
    $mix = "AND mix.brand_name='" . $_GET['brand'] . "'";
} else {
    $mix = '';
}
/* end color and brand by Socheat ngann */
// price between
$priceFrom = isset($_GET['pfrom']) ? $_GET['pfrom'] : '';
$priceTo = isset($_GET['pto']) ? $_GET['pto'] : '';
if ($priceFrom != '' and $priceTo != '') {
    $s_price = 'AND pip.`price` BETWEEN ' . $priceFrom . ' AND ' . $priceTo . '';
} else {
    if ($priceFrom != '') {
        $s_price = 'AND pip.`price` >= ' . $priceFrom . '';
    } else if ($priceTo != '') {
        $s_price = 'AND pip.`price` <= ' . $priceTo . '';
    } else {
        $s_price = '';
    }
}
/* price between  by Socheat ngann */

/* by Province */
$get_province = (int) isset($_GET['province']) ? $_GET['province'] : '';
if (!empty($get_province)):
    $sql_provice = ' AND p.' . Tblproduct::province_id . '=' . $get_province;
else:
    $sql_provice = '';
endif;
/* end by Province  by Socheat ngann */
/* by disctict */
$get_district = (int) isset($_GET['district']) ? $_GET['district'] : '';
if (!empty($get_district)):
    $sql_district = ' AND p.' . Tblproduct::district_id . '=' . $get_district;
else:
    $sql_district = '';
endif;
/* end by disctict by Socheat ngann */

/* by new or used pro */
$get_buy_sell = (int) isset($_GET['new_old']) ? $_GET['new_old'] : '';
if (!empty($get_buy_sell)):
    $sql_buy_sell = ' AND p.' . Tblproduct::product_version . '=' . $get_buy_sell;
else:
    $sql_buy_sell = '';
endif;
/* end by new or used pro by Socheat ngann */

/* Order by */
$get_order = isset($_GET['order']) ? $_GET['order'] : '';
$get_sort = isset($_GET['sort']) ? $_GET['sort'] : '';
if (!empty($get_order)):
    $sql_order = ' ORDER BY ' . $get_sort . ' ' . $get_order;
else:
    $sql_order = ' ORDER BY p.post_type DESC';
endif;

if (preg_match('/limit/', $CURRENT_URL)):
    $limit_url = explode('limit', $CURRENT_URL);
    $get_limit_url = $limit_url[0];
endif;
/* Order by Socheat ngann */

/* show limit */
$limit_select = (int) ((!empty($_GET['num'])) ? $_GET['num'] : '30');
/* end show limit */

/* search by name */
$pro_name = isset($_GET['search']) ? $_GET['search'] : '';
$pro_name = preg_replace("/<!--.*?-->/", "", $pro_name);
if (!empty($pro_name)):
    $sql_name = " AND p.product_name LIKE '$pro_name%'";
else:
    $sql_name = '';
endif;
/* end search by name */
if (!empty($category)) {
    $category = " pic.category_id IN ($category) AND";
} else {
    $category = '';
}
$rowsPerPage = isset($_GET['num']) ? $_GET['num'] : $limit_select;
$select = ("SELECT p.product_type, p.product_name, pic.product_id, pic.category_id, img.thumbnail,img.images, pip.price, pip.country_id,p.id,pip.pid,p.product_version
				FROM `tblproduct` AS p LEFT JOIN `tblimage` AS img ON p.id = img.product_id
				INNER JOIN `tblproduct_in_pharmacy` AS pip ON p.id = pip.product_id
				LEFT JOIN tblproduct_in_category AS pic ON p.id = pic.product_id
				LEFT JOIN tbl_color_size AS mix ON mix.pid=p.id
				WHERE $category pip.status = 1 $mix $s_price $sql_provice $sql_district $sql_buy_sell $sql_name $sql_user GROUP BY p.id $sql_order");
$result_product = mysql_query(getPagingQuery($select, $rowsPerPage));

$Page_link = base_url . 'product' . $userlink;
$pagingLink = getPagingLink($select, $rowsPerPage, $qstring, $Page_link);
if (!empty($_GET['cat_id'])) {
    $catid = '&cat_id=' . $_GET['cat_id'];
}
if (!empty($_GET['cat_p'])) {
    $cat_idp = '&cat_p=' . $_GET['cat_p'];
} else {
    $cat_idp = '';
}
?>
<div class="breadcrumb">
    <a class="lever_1" style="z-index:100" href="<?php echo base_url; ?>"><?php echo $lang['HOME']; ?></a>
    <a class="lever_2" style="z-index:99" href="<?php echo base_url; ?>product"><?php echo $lang['UR_PRO_LIST']; ?></a>
    <?php if (!empty($user_id)): ?>
        <a class="lever_3" style="z-index:98" href="<?php echo base_url; ?><?php echo $row_user[Tblcompany::shorturl]; ?>"><?php echo ((!empty($company_name)) ? $company_name : $lang['USER_PRODUCT']); ?></a>
    <?php endif; ?>
    <?php
    if (!empty($parent)): get_crumbs($parent, 0, $cat_id);
    endif;
    ?>
</div>
<?php
if (!empty($parent)) {
    $cat_Sub = (!empty($_GET['sub']) ? $_GET['sub'] : '');
    if (empty($cat_Sub)) {
        include(S_ROOT . '/includefiles/browser.php');
    }
}
?>
<div class="row-fluid">
    <?php include(S_ROOT . '/templates/sidebar-left.php'); ?>
    <div class="span12 category">
        <div id="content">
            <div class="title">
                <h1 class="category-title"><?php
                    if (!empty($parent)):
                        echo special_char(getCategoryName($parent));
                    elseif (!empty($parent)):
                        echo $searchby;
                    else:
                        echo ((!empty($company_name)) ? $company_name : $lang['USER_PRODUCT']);
                    endif;
                    ?></h1>
            </div>
            <?php if (!empty($user_id) && $user_id!='none') {?>
            <div class="row-fluid user-p-query">
                <div class="span12">
                    <div class="alert alert-block fade in">
                        <button type="button" class="close"><a href="<?php echo base_url . 'product/?user=none'; ?>" style="color:#000">X</a></button>
                        <h3 class="alert-heading">Browsing by user: &quot; <b style="font-size: 110%;"><?php if(!empty($company_name)){ echo $company_name;} else {echo 'no-name';}?></b> &quot;</h3>
                    </div>
                </div>
            </div>
            <?php }?>
            <div class="product-filter">
                <div class="display"><b>Display:</b> <a onclick="display('list');">List</a> <b>/</b> Grid</div>
                <div class="limit"><b>Show:</b>
                    <select onchange="location = this.value;">
                        <?php
                        $num_limit = array(15, 25, 30, 50, 75, 100);
                        foreach ($num_limit as $key => $value):
                            ?>
                            <option value="<?php echo base_url . 'product/'; ?>?searchby=1&num=<?php echo $value; ?>" <?php
                            if ($limit_select == $value): echo 'selected="selected"';
                            endif;
                            ?>><?php echo $value; ?></option>
                                <?php endforeach; ?>
                    </select>
                </div>
                <div class="sort"><b>Sort By:</b>
                    <?php
                    if (preg_match('/sort/', $CURRENT_URL)):
                        $limit_url = explode('sort', $CURRENT_URL);
                        $get_order_url = $limit_url[0];
                        $select_order_url = $limit_url[1];
                    else:
                        $get_order_url = '';
                        $select_order_url = '';
                    endif;
                    ?>
                    <select onchange="location = this.value;">
                        <option value="<?php echo base_url . 'product/'; ?>">Default</option>
                        <option value="<?php echo base_url . 'product/'; ?>?searchby=1&sort=p.product_name&order=ASC" <?php echo (($select_order_url == '=p.product_name&order=ASC') ? 'selected="selected"' : '') ?>>Name (A - Z)</option>
                        <option value="<?php echo base_url . 'product/'; ?>?searchby=1&sort=p.product_name&order=DESC" <?php echo (($select_order_url == '=p.product_name&order=DESC') ? 'selected="selected"' : '') ?>>Name (Z - A)</option>
                        <option value="<?php echo base_url . 'product/'; ?>?searchby=1&sort=pip.price&order=ASC" <?php echo (($select_order_url == '=pip.price&order=ASC') ? 'selected="selected"' : '') ?>>Price (Low &gt; High)</option>
                        <option value="<?php echo base_url . 'product/'; ?>?searchby=1&sort=pip.price&order=DESC" <?php echo (($select_order_url == '=pip.price&order=DESC') ? 'selected="selected"' : '') ?>>Price (High &gt; Low)</option>
                        <option value="<?php echo base_url . 'product/'; ?>?searchby=1&sort=&new_old=0" <?php echo (($select_order_url == '=&new_old=0') ? 'selected="selected"' : '') ?>>New</option>
                        <option value="<?php echo base_url . 'product/'; ?>?searchby=1&sort=&new_old=1" <?php echo (($select_order_url == '=&new_old=1') ? 'selected="selected"' : '') ?>>Old</option>
                    </select>
                </div>
                <div class="clear"></div>
                <form class="form-horizontal visible-desktop">
                    <input type="hidden" value="1" name="searchby"/>
                    <div class="row-fluid current-cat" style="margin-top:5px;">
                        <div class="span12">
                            <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" style="padding: 0;border: none; margin: 10px 0;">
                                <tbody><tr>
                                        <td class="tdprice" align="right" style="width:10px; padding:8px 0 0 3px">$
                                            <span style="text-align: center"></span></td>
                                        <td class="tdprice" align="right" style="padding: 2px 10px 2px 2px;"><input type="text" name="pfrom" placeholder="From" style="height: 26px;width: 80px"></td>
                                        <td class="tdprice" align="center" style="width:25px; padding:8px 0">to $</td>
                                        <td class="tdprice" align="left" style="padding: 2px 10px 2px 2px;"><input type="text" name="pto" placeholder="To" style="height: 26px;width: 80px"></td>
                                        <td>
                                            <select name="cat_id" style="width: 100%" class="option_drop">
                                                <option value=""><!--Options--><?php echo $lang['MENU_CATEGORY']; ?></option>
                                                <?php
                                                build_tree_drop($parent_id = 0, $level = 0, $cat_id);
                                                ?>
                                            </select>
                                        </td>
                                        <td class="td-province">
                                            <?php
                                            $table = Tblprovince::tblprovince;
                                            $province = select($table);
                                            ?>
                                            <select class="form_locate_province" name="province" id="Phovince" style="width: 100%;">
                                                <option value=""><?php echo $lang['SHIP_PRO_STATE']; ?></option>
                                                <?php while ($result_pro = mysql_fetch_array($province)) { ?>
                                                    <option value="<?php echo $result_pro[Tblprovince::id]; ?>" data-id="<?php echo $result_pro[Tblprovince::lat_long]; ?>" <?php echo($result_pro[Tblprovince::id] == $get_province) ? ' selected="selected"' : '' ?>><?php echo $result_pro[Tblprovince::name]; ?></option>
                                                <?php } ?>
                                            </select>
                                        </td>
                                        <td class="td-district">
                                            <select class="form_locate_district" name="district" id="District" style="float: left;width: 100%;">
                                                <option value="">District</option>
                                                <?php
                                                $districts = '';
                                                $district = select(Tblstate::tblname);
                                                while ($dis_data = mysql_fetch_assoc($district)) :
                                                    ?>
                                                    <option value="<?php echo $dis_data[Tblstate::id]; ?>" <?php echo($dis_data[Tblstate::id] == $get_district) ? ' selected="selected"' : '' ?>><?php echo $dis_data[Tblstate::name]; ?></option>
                                                <?php endwhile; ?>
                                            </select>
                                            <div id="loading" style="display: none;"><img src="<?php echo base_url; ?>images/img/colorbox/loading.gif"/></div>
                                        </td>
                                        <td>
                                            <button class="btn" type="submit" style="width: 100%; height: 30px"><div class="icon-search"></div></button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </form>
            </div>

            <div class="row-fluid">
                <?php
                $count_sub_cat = 0;
                $cat_c = $cat_p;
                $cat_p = (!empty($_GET['sub']) ? $_GET['sub'] : $cat_p);
                if (!empty($cat_p)) {
                    $check_sub_cat = select(Tblcategory::TableName, '', $where = array(Tblcategory::parent_id => $cat_p));
                    $count_sub_cat = mysql_num_rows($check_sub_cat);
                }
                if (!empty($count_sub_cat)):
                    ?>
                    <div class="span3">
                        <?php
                        $get_cat_sub = get_current_cat($cat_p, 0, $cat_c, $cat_p);
                        if (!empty($get_cat_sub)) {
                            ?>
                            <div class="row-fluid current-cat">
                                <div class="sub-cat-in">
                                    <ul>
                                        <?php
                                        if ($pageURL != $homepage) {
                                            echo $get_cat_sub;
                                        }
                                        ?>
                                    </ul>
                                </div>
                                <style>
                                    .current-cat {margin-top: 20px}
                                    .sub-cat-in ul{padding:0;margin:0}
                                    .sub-cat-in li {list-style-type: none;}
                                    .active, .sub-cat-in li a{padding:5px 5px 5px 8px;border-bottom: 1px solid #eee;display: block}
                                    .sub-cat-in li a:hover{background:#f89406;color: #fff}
                                </style>
                            </div>
                        <?php } ?>
                    </div>
                <?php endif; ?>
                <div class="<?php echo (!empty($count_sub_cat) ? 'span9' : 'span12'); ?>">
                    <div class="product-grid">
                        <?php
                        $i = 1;
                        if (!empty($result)) {
                            while ($data = mysql_fetch_assoc($result_product)) {
                                $pharmacy = mysql_query("SELECT COUNT(DISTINCT pharmacy_id) AS pid
                        FROM tblproduct_in_pharmacy WHERE product_id=" . (int) $data['id'] . " AND country_id=" . (int) $data['country_id']);

                                $price = mysql_query("SELECT price,regular_price FROM tblproduct_in_pharmacy WHERE product_id=" . (int) $data['id'] . " ORDER BY price ASC LIMIT 0,1");
                                $myprice = mysql_fetch_assoc($price);
                                $price1 = mysql_query("SELECT price,regular_price FROM tblproduct_in_pharmacy WHERE product_id=" . (int) $data['id'] . " ORDER BY price DESC LIMIT 0,1");
                                $myprice1 = mysql_fetch_assoc($price1);
                                if ($i % 4 == 1) {
                                    echo '<div class="row-fluid box-product">';
                                }
                                ?>
                                <div class="span3 product_block">
                                    <?php echo showProduct($data, $myprice, $cat_id);?>
                                    <span class="label <?php echo ($data[Tblproduct::product_version] == 1) ? '' : 'label-warning'; ?> prodct-type"><?php echo ($data[Tblproduct::product_version] == 1) ? $lang['PRO_STATUS_USED'] : $lang['PRO_STATUS_NEW']; ?></span>
                                </div>
                                <?php
                                if ($i % 4 == 0) {
                                    echo "</div>";
                                }
                                $i++;
                            }
                            if ($i % 4 != 1)
                                echo "</div>";
                        } else {
                            ?>

                            <div style="margin-left:15px;">
                                <div class="twelve columns">
                                    <div class="bo_eee radius1 ba_fff pad_10" style="margin-right: 15px; margin-bottom:15px;">
                                        <h3 align="center" style="text-align:center;">No Product in <?php echo getCategoryName($category_id); ?> </h3>
                                    </div>
                                </div>
                            </div>

                            <?php
                        }
                        ?>
                    </div>
                </div>
            </div>
            <hr />
            <?php include(S_ROOT . '/includefiles/sup_bottom_advertise.php'); ?>
        </div>
        <?php if (!empty($pagingLink)) {
            ?>
            <div style="clear:both;text-align: center" align="center">
                <div class="span12">
                    <div class="box">
                        <div class="pagination">
                            <div class="links">
                                <?php echo $pagingLink; ?>
                            </div>
                            <div class="clear"></div>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        }
        ?>
    </div>
</div>
<script type="text/javascript">
        $(document).ready(function() {
            /*Get Disrtict*/
            $("#Phovince").change(function()
            {
                var id = $(this).val();
                var dataString = 'id=' + id;
                var gid = $('option:selected', this).attr('data-id');
                $('#loading').show();
                $.ajax
                        ({
                            type: "POST",
                            url: "<?php echo base_url; ?>account/ajax_district.php?action=byprovince",
                            data: dataString,
                            cache: false,
                            success: function(html)
                            {
                                $("#District").html(html);
                                $("#District").removeAttr("disabled");
                                $('#loading').hide();
                            }
                        });
            });
            /*end Get Disrtict*/
        });

        function display(view) {
            if (view == 'list') {
                $('#content .product-grid').attr('class', 'product-list');

                $('.product-list div.product_block').each(function(index, element) {
                    html = '';
                    var image = $(element).find('.image').html();
                    var prodcttype = $(element).find('.prodct-type').html();

                    if (prodcttype != null) {
                        html += '<span class="label label-info prodct-type" style="top:0!important">' + prodcttype + '</span>';
                    }
                    if (image != null) {
                        html += '<div class="image pull-left">' + image + '</div>';
                    }

                    html += '<div class="wrap-infor ">';
                    html += '  <div class="name">' + $(element).find('.name').html() + '</div>';
                    var price = $(element).find('.price').html();

                    if (price != null) {
                        html += '<div class="price">' + price + '</div>';
                    }

                    html += '</div>';

                    $(element).html(html);
                });

                $('.display').html('<b>Display:</b> List <b>/</b> <a onclick="display(\'grid\');">Grid</a>');

                $.totalStorage('display', 'list');
            } else {
                $('#content .product-list').attr('class', 'product-grid');

                $('.product-grid div.product_block').each(function(index, element) {
                    html = '';

                    var image = $(element).find('.image').html();

                    if (image != null) {
                        html += '<div class="product-inner"><div class="image">' + image + '</div>';
                    }
                    var prodcttype = $(element).find('.prodct-type').html();

                    if (prodcttype != null) {
                        html += '<span class="label label-info prodct-type">' + prodcttype + '</span>';
                    }
                    html += '<div class="wrap-infor"><div class="name">' + $(element).find('.name').html() + '</div>';

                    var price = $(element).find('.price').html();

                    if (price != null) {
                        html += '<div class="price">' + price + '</div>';
                    }
                    $(element).html(html);
                });

                $('.display').html('<b>Display:</b> <a onclick="display(\'list\');">List</a> <b>/</b> Grid');

                $.totalStorage('display', 'grid');
            }
        }
        view = $.totalStorage('display');
        if (view) {
            display(view);
        } else {
            display('grid');
        }
</script>
<style>
    #columns img{max-width: 100%;}
    .user-p-query{margin-top: 15px;}
    .user-p-query .alert{margin-bottom: 0;}
</style>